<template>
  <el-upload
    ref="upload"
    v-model:file-list="fileList"
    class="upload-comp leading-[20px] w-[100%]"
    action="#"
    :limit="limit"
    :on-exceed="handleExceed"
    :before-upload="beforeUpload"
    :on-success="handleSuccess"
    :http-request="handleHttpRequest"
    v-bind="$attrs"
  >
    <template v-if="slots.includes('content')">
      <slot name="content"></slot>
    </template>
    <template v-else>
      <div class="flex flex-1 items-center justify-between">
        <div class="flex items-center">
          <span
            class="text-[14px] text-[var(--el-text-color-regular)] leading-[22px] font-[700]"
          >
            {{ label }}<span class="text-[#E50113]" v-if="require">*</span>
          </span>
          <el-divider direction="vertical" />
          <div class="pointer-cursor text-[14px] text-[#333]">
            <span class="iconfont icon-upload mr-[4px]"></span>
            <span>上传附件</span>
          </div>
        </div>
        <div>
          <slot name="headRight"></slot>
        </div>
      </div>
    </template>

    <template #file="{ file }">
      <span>{{ file.name }}</span>
      <span class="text-[#3487FF] cursor-pointer">
        <span class="mx-[16px]" @click.stop="handleDown(file.url)">下载</span>
        <span class="text-[#E50113] ml-[8px]" @click="handleDelete(file)">
          <svg-icon icon-class="del" class="inline-block"></svg-icon>
        </span>
      </span>
    </template>
    <template #tip v-if="!fileList.length && isTip">
      <div class="el-upload__tip text-[#ccc] text-[14px] leading-[20px]">
        尚未添加附件
      </div>
    </template>
  </el-upload>
</template>

<script setup>
import { genFileId, ElMessage } from "element-plus";
const props = defineProps({
  label: { type: String, default: "附件" },
  require: { type: Boolean, default: false },
  limit: { type: Number, default: 1 },
  modelValue: { type: Array, default: () => [] },
  isTip: { type: Boolean, default: true },
});
let slots = computed(() => Object.keys(useSlots()));
const emit = defineEmits(["update:modelValue"]);

import { uploadFlieMsg, downFlieMsg } from "@/api/public.js";

const upload = ref();
const fileList = ref([]);

watch(
  () => props.modelValue,
  (val) => {
    fileList.value = val;
  }
);

watch(
  () => fileList.value,
  (val) => {
    emit("update:modelValue", val.length ? val : undefined);
  },
  {
    immediate: true,
    deep: true,
  }
);

const beforeUpload = (file) => {
  const limitSize = 50;
  const isLt500M = file.size / 1024 / 1024 < limitSize;
  if (!isLt500M) {
    ElMessage.error(`上传文件大小不能超过 ${limitSize}MB!`);
  }
  return isLt500M;
};

const handleHttpRequest = async (options) => {
  let formData = new FormData();
  const { file } = options;
  formData.append("file", file);
  formData.append("alias", "notice-message-private");
  try {
    const { data } = await uploadFlieMsg(formData);
    return data;
  } catch (e) {
    console.error(e);
    options.onError(e);
  }
};

const handleExceed = (files) => {
  upload.value.clearFiles();
  const file = files[0];
  file.uid = genFileId();
  upload.value.handleStart(file);
  upload.value.submit();
};

const handleSuccess = (_res, _file, _fileList) => {
  processFileList(_fileList);
};

const processFileList = (_fileList) => {
  const _data = _fileList.map((item) => {
    return {
      uid: item.uid,
      name: item.name,
      url: item?.response || item.url,
      size: item.size,
    };
  });
  fileList.value = _data;
};

const handleDelete = (e) => {
  const _data = fileList.value;
  const _index = _data.findIndex((n) => n.uid === e.uid);
  fileList.value.splice(_index, 1);
};

const handleDown = async (_url) => {
  const { data } = await downFlieMsg({
    alias: "notice-message-private",
    fileKey: _url,
  });
  if (data) window.open(data, "noopener", "noreferrer");
};
const clearFiles = () => {
  upload.value.clearFiles();
};
defineExpose({ clearFiles });
</script>
<style lang="scss" scoped>
.upload-comp {
  :deep(.el-upload) {
    line-height: 20px;
    width: 100%;
  }
}
</style>
